<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');







/**
 * 生成完整图片 腾讯COS HTTP路径
 * @return  string
 */
/*function get_image_cos($image, $default_img = 'no_picture')
{
	$_this =& get_instance();
    if(!empty($image)){
		$re_image = $_this->config->item('imageurl') . $image;
	}else{
	    $default_image = full_static_url($_this->config->item($default_img));
		$re_image = $default_image;
	}
	return $re_image;
}*/


/**
 * 生成完整图片 本服务器HTTP路径
 * @return  string
 */
function get_image_path($image, $default_img = 'no_picture')
{
	$CI =& get_instance();
	$valid_img = array('no_picture', 'no_user_avatar', 'no_staff_avatar');
	if(!in_array($default_img, $valid_img)){
		$default_img = 'no_picture';
	}
	$default_image = full_static_url($CI->config->item($default_img));
	//return get_cfg('sub_project');
	if(!empty($image)){
		if(strpos($image, 'http://') === FALSE){
			if(@is_file(full_static_path($image))){
				//图片存在当前系统目录下
				$re_image = full_static_url($image);
			}else{
				//图片在指定资源目录下
				$static_path = $CI->config->item('static_path');
				if(!empty($static_path)){
					$re_image = $static_path . $image;
				}else{
					$re_image = full_static_url($image);
				}
			}
		}else{
			$re_image = $image;
		}
	}else{
		$re_image = $default_image;
	}
	return $re_image;
}

/**
 * 获取资源的完整URL http://****
 * @param unknown $source_path
 */
function full_static_url($source_path)
{
	$sub_project = get_instance()->config->item('sub_project');
	$path = site_url(format_static_path($source_path));
	if(!empty($sub_project)){
		$path = str_replace("$sub_project/", '', $path);
	}
	return $path;
}
/**
 * 获取资源的完整访问路径 服务器端本地路径
 * @param unknown $source_path
 */
function full_static_path($source_path)
{
	$sub_project = get_instance()->config->item('sub_project');
	$path = FCPATH;
	if(!empty($sub_project)){
		$path = str_replace(array("$sub_project/", "$sub_project\\"), '', $path);
	}
	return $path . format_static_path($source_path);
}
/**
 * current(str_split($static_dir)) !== '/'
 * 给文件路径加上 定义的 资源目录
 * @param unknown $source_path
 * @return string
 */
function format_static_path($source_path){
	$static_dir = get_instance()->config->item('resource_dir');
	$static_dir = '/'.ltrim($static_dir, '/');
	$source_path = '/'.ltrim($source_path, '/');

	return $static_dir . $source_path;
}
/**
 *  分配图片子目录（按item_id取余）
 *	$item_id
 *	$folder_nums 	定义子目录个数
 *
 */
function assign_sub_img_folder($item_id, $folder_nums = 4)
{
	$letters = "abcdefghijkmlnopqrstuvwxyz";
	$sub_name = $item_id % $folder_nums;
	return $letters{$sub_name} . '/' . $item_id . '/';
}
/**
 * 将上传文件分类整理到相应目录
 * @param unknown $item_id
 * @param unknown $image_type
 * @param unknown $source_img
 * @param string $return_path
 * @return string
 */
function reformat_image_name($item_id, $image_type, $source_img, $return_path = false)
{
	$img_dir = "images";//默认图片存储目录
	$file_ext = pathinfo($source_img, PATHINFO_EXTENSION);
	$has_date_folder = true;
	$data_path = '/' . date('Y', gmtime()) . '-' .date('m', gmtime()).'/';
	$name_type = 'default';
	switch($image_type){
		case 'helper_gallery_thumb':
		case 'helper_gallery_image':
		case 'helper_gallery':
            $has_date_folder = false;
			$img_dir .= '/helper_gallery/' . get_mon() . '/';
			$symbolArr = array('helper_gallery_thumb' => 'T','helper_gallery_image' => 'I','helper_gallery' => 'O');
			$symbol = '_'.$symbolArr[$image_type].'_';
			break;
		default:
			$symbol = '_I_';
			break;
	}
	if($has_date_folder){
		$img_dir .= $data_path;//以日期为子目录
	}
	switch($name_type)
	{
		case 'tour':
			$file_name = $item_id . $symbol . random_str(6, 'upper');
			break;
		default:
// 			$rand_name = gmtime() . random_str(6, 'num-upper');
			$rand_name = substr(md5(microtime()), 8, 10);// . random_str(4, 'num-upper');
			$file_name = $item_id . $symbol . $rand_name;
			break;
	}
	$file_name .= "." . $file_ext;
	if(make_dir(full_static_path($img_dir))){
		return $img_dir . $file_name;
	}else{
		return false;
	}	
}
    //$type = 2 获取今天(20150901) 或 $type = 1 当前月(201509)
    function get_mon($type = 1){
        if($type == 1){
            return date("Ym", time());
        }else{
            return date("Ymd", time());
        }
        
    }
/**
 * 将上传文件转移到指定位置
 *
 * @param string $file_name
 * @param string $target_name
 * @return blog
 */
function move_upload_file($file_name, $target_name = '')
{
	if (function_exists("move_uploaded_file"))
	{
		if (move_uploaded_file($file_name, $target_name))
		{
			@chmod($target_name,0755);
			return true;
		}
		else if (copy($file_name, $target_name))
		{
			@chmod($target_name,0755);
			return true;
		}
	}
	elseif (copy($file_name, $target_name))
	{
		@chmod($target_name,0755);
		return true;
	}
	return false;
}
/**
 * 检查目标文件夹是否存在，如果不存在则自动创建该目录
 * @access      public
 * @param       string      folder     目录路径。不能使用相对于网站根目录的URL
 * @return      bool
 */
function make_dir($folder)
{
	$reval = false;
	if (!file_exists($folder)){
		/* 如果目录不存在则尝试创建该目录 */
		@umask(0);
		/* 将目录路径拆分成数组 */
		preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);
		/* 如果第一个字符为/则当作物理路径处理 */
		$base = ($atmp[0][0] == '/') ? '/' : '';
		/* 遍历包含路径信息的数组 */
		foreach ($atmp[1] AS $val){
			if ('' != $val){
				$base .= $val;
				if ('..' == $val || '.' == $val){
					/* 如果目录为.或者..则直接补/继续下一个循环 */
					$base .= '/';
					continue;
				}
			}else{
				continue;
			}
			$base .= '/';
			if (!file_exists($base)){
				/* 尝试创建目录，如果创建失败则继续循环 */
				if (@mkdir(rtrim($base, '/'), 0777)){
					@chmod($base, 0777);
					$reval = true;
				}
			}
		}
	}else{
		/* 路径已经存在。返回该路径是不是一个目录 */
		$reval = is_dir($folder);
	}
	clearstatcache();
	return $reval;
}
function temp_files()
{
	$CI =& get_instance();
	$CI->load->model('file_model');
	$filter['sort_order'] = 'file_id asc';
	$result = $CI->file_model->get_list($filter);
	return $result;
}

//上传文件至腾讯云服务器
//$file_dri 图片路径 /images/canteen_image/201509/5A09FCA4680F29793332.PNG

/*function file_txy($file_dri){
    $_this =& get_instance();
    $bucketName = $_this->config->item('ENVIRONMENT');
    $_this->load->library('myqcloudcos');
    $re = $_this->myqcloudcos->upload(full_static_path($file_dri), $bucketName, '/' . $file_dri);
   // var_dump($re);
    if($re['code'] == 0){
        return 0;
    }else{
        return 1;//上传失败
    }
}*/

/**
 * 阿里云OSS上传
 * @param $file_dri 上传文件路径'images/xxx/xxx/aa.jpg'，也就是阿里云中的路径
 * @return int
 */
function file_txy($file_dri){
	$_this =& get_instance();
	$param = [
		'accessKeyId'=>$_this->config->item('ali_oss_accesskeyid'),
		'accessKeySecret'=>	$_this->config->item('ali_oss_accesskeysecret'),
		'endpoint'=>$_this->config->item('ali_oss_endpoint'),
		'isCName'=>$_this->config->item('ali_oss_iscname'),
		'securityToken'=>$_this->config->item('ali_oss_securitytoken')
	];
	$_this->load->library('AliyunOssClient',$param,'AliyunOssClient');
	$bucket = $_this->config->item('ali_oss_bucket');
	try {
		$_this->AliyunOssClient->uploadFile($bucket, $file_dri, full_static_path($file_dri));
		return 0;
	} catch (OSS\Core\OssException $e) {
		print $e->getMessage();
		return 1;//上传失败
	}

}
